import logging.handlers
import os
from datetime import datetime

from ApiAutoTestPlatform import settings


class GetLog:
    # 定义logger
    __logger = None

    # 获取logger
    @classmethod
    def get_logger(cls):
        if cls.__logger is None:
            # 获取日志器
            cls.__logger = logging.getLogger()
            # 设置级别
            cls.__logger.setLevel(logging.INFO)
            # 日志输出位置
            filepath = settings.BASE_DIR + os.sep + 'templates' + os.sep + 'log' + os.sep + \
                       datetime.now().strftime('%Y-%m-%d') + '-autotest.log'
            # 获取处理器
            th = logging.handlers.TimedRotatingFileHandler(filename=filepath,
                                                           when='midnight',
                                                           interval=1,
                                                           backupCount=30,
                                                           encoding='utf-8')
            # 获取格式器
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fm = logging.Formatter(fmt)
            # 将格式器放入 处理器
            th.setFormatter(fm)
            # 将处理器添加到日志器
            cls.__logger.addHandler(th)
        return cls.__logger
